﻿using PRO.Cache;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;

namespace PRO.DbProvider
{
    public class DataBaseProvider
    {
        private DataBaseProvider() { }
        private static IDataProvider _instance = null;
        private static object lockHelper = new object();
        static DataBaseProvider()
        { 
            
        }
        #region 数据访问层-使用一个接口
        private static void GetProvider()
        {
            _instance = (IDataProvider)Activator.CreateInstance(Type.GetType("PRO.Data.SqlServer.DataProvider,PRO.Data.SqlServer", false, true));
        }
        /// <summary>
        /// 获取数据处理层实例
        /// </summary>
        /// <returns></returns>
        public static IDataProvider GetInstance()
        {
            if (_instance == null)
            {
                lock (lockHelper)
                {
                    if (_instance == null)
                        GetProvider();
                }
            }
            return _instance;
        }
        /// <summary>
        /// 重置实例
        /// </summary>
        public static void ResetDbProvider()
        {
            _instance = null;
        }
        #endregion

        #region 使用工厂模式-多个接口使用
        /// <summary>
        /// 创建对象
        /// </summary>
        /// <param name="AssemblyPath">命名空间，示例：PRO.Data.SqlServer</param>
        /// <param name="classNamespace">类名，示例：DataProvider</param>
        /// <returns></returns>
        public static object CreateObject(string AssemblyPath, string classNamespace)
        {
            object obj = PROCache.GetCacheService().RetrieveOriginObject(classNamespace);
            if (obj == null)
            {
                try
                {
                    obj = Activator.CreateInstance(Type.GetType(AssemblyPath + "." + classNamespace + "," + AssemblyPath, false, true));
                    //或者使用
                    //obj = Assembly.Load(AssemblyPath).CreateInstance(AssemblyPath + "." + classNamespace);
                    PROCache.GetCacheService().AddObject(classNamespace, obj);
                }
                catch
                {
                    return null;
                }
            }
            return obj;
        }

        //此处创建各个对象

        /// <summary>
        /// 创建公共方法数据库访问对象
        /// </summary>
        /// <returns></returns>
        public static IPublicProvider CreatePublic()
        {
            return ((IPublicProvider)DataBaseProvider.CreateObject("PRO.Data.SqlServer", "PublicManager"));
        }
        #endregion
    }
}
